<template>
  <div class="pad-20 bgc-default">
    <div class="pad-20 bg-color-white">
      <div>
        <el-button @click="doAdd('')" type="primary">新增</el-button>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate mar-t-20">
        <div class="search-item">
          <el-select v-model="searchListQuery.moduleCode" placeholder="请选择功能" >
            <el-option v-for="(val, key) in dict.module" :key="key" :label="val" :value="key"></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model.trim="searchListQuery.attributeName" placeholder="请输入属性标题"></el-input>
          <el-select v-model="searchListQuery.attributeType" placeholder="请选择属性类型" >
            <el-option label="全部" value=""></el-option>
            <el-option v-for="(val, key) in dict.attributeType" :key="key" :label="val" :value="key"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="dataList" v-loading="listLoading"
          element-loading-text="加载中" header-cell-class-name="default-header" row-class-name="default-row">
          <el-table-column min-width="220px" label="功能" fixed="left">
            <template slot-scope="scope">
              {{ dict.module[scope.row.moduleCode] }}
            </template>
          </el-table-column>
          <el-table-column min-width="220px" label="属性标题" prop="attributeName" align="left">
          </el-table-column>
          <el-table-column min-width="100px" label="属性类型" align="center">
            <template slot-scope="scope">
              {{ dict.attributeType[scope.row.attributeType] }}
            </template>
          </el-table-column>
          <el-table-column min-width="100px" label="必填" align="center">
            <template slot-scope="scope">
              {{ scope.row.attributeValueNullable == 1 ? '否' : '是' }}
            </template>
          </el-table-column>
          <el-table-column min-width="220px" label="默认值" align="center">
            <template slot-scope="scope">
              {{ scope.row.attributeType == 'select' ? scope.row.attributeDefaultValueText : scope.row.attributeDefaultValue }}
            </template>
          </el-table-column>
          <el-table-column min-width="200px" label="操作" fixed="right" header-align="center" align="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="doAdd(scope.row)">编辑</el-button>
              <el-button type="text" size="medium" v-if="scope.$index != 0 || searchListQuery.currentPage > 1" @click="doMove(scope.row, 'up')">上移</el-button>
              <el-button type="text" size="medium" v-if="(scope.$index + 1) + ((searchListQuery.currentPage - 1) * searchListQuery.size) < total" @click="doMove(scope.row, 'down')">下移</el-button>
              <el-button type="text" size="medium" @click="doDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="dialogTitle" v-el-drag-dialog :visible.sync="customFormVisible" :close-on-press-escape="true" :center="true" width="650px">
      <el-form ref="customForm" :model="customForm" label-position="right" :rules="rules" label-width="120px">
        <el-form-item label="功能：" prop="moduleCode">
          <el-select v-model="customForm.moduleCode" class="width-per-80" :disabled="customForm.attributeId != ''" placeholder="请输入所属功能">
            <el-option v-for="(val, key) in dict.module" :key="key" :label="val" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性标题：" prop="attributeName">
          <el-input v-model="customForm.attributeName" class="width-per-80" maxlength="20" placeholder="请输入属性标题"></el-input>
        </el-form-item>
        <el-form-item label="属性类型：" prop="attributeType">
          <el-select v-model="customForm.attributeType" @change="attributeTypeChange" class="width-per-80" :disabled="customForm.attributeId != ''" placeholder="请输入属性类型">
            <el-option v-for="(val, key) in dict.attributeType" :key="key" :label="val" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认值：" prop="attributeDefaultValue">
          <el-input v-model="customForm.attributeDefaultValue" class="width-per-80" maxlength="20"></el-input>
          <el-tooltip effect="dark" placement="top">
            <div slot="content">
              <span>文字：填入要显示的默认文字</span>
              <br/>
              <span>选项：填入默认选中选项的键值</span>
              <br/>
              <span>日期：填入默认日期，如：2020-01-01</span>
              <br/>
              <span>勾选：默认勾选填入1，不勾选填入0</span>
              <br/>
            </div>
            <i class="el-icon-info font-16 font-blue mar-l-10"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label=" ">
          <el-checkbox v-model="customForm.nullable">属性值不能为空</el-checkbox>
        </el-form-item>
        <el-form-item label="选项：" v-if="optionShowFlag">
          <div>
            <span class="font-color-9 font-12">仅当类型为“选项”时，需要填写选项值，键值可由数字或字母组成。&nbsp;&nbsp;</span>
            <el-button type="text" class="font-12" size="medium" @click="doAddOption()">新增</el-button>
          </div>
          <div class="mar-b-10 flex option-block" v-for="(item, index) in customForm.optionList" :key="index">
            <el-form-item label="标题：" :prop="'optionList.'+index+'.optionName'" :rules="rules.optionName" label-width="50">
              <el-input v-model="item.optionName" class="width-110" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="键值：" :prop="'optionList.'+index+'.optionValue'" :rules="rules.optionValue" class="mar-l-10" label-width="50">
              <el-input v-model="item.optionValue" class="width-110" :disabled="item.optionId != ''" maxlength="20"></el-input>
            </el-form-item>
            <el-button type="text" size="medium" class="mar-l-10 font-12" v-if="item.optionId == '' || item.allowDelFlag == 1" @click="doDeleteOption(item)">删除</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doSave">保存</el-button>
        <el-button @click="customFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import elDragDialog from '@/directive/el-dragDialog'
  import { getDictByGroupName } from '@/api/common/common'
  import { pagingAttribute, getAttribute, saveAttribute, doMoveUpdate, deleteAttribute } from '@/api/custom/customAttribute'

  export default {
    directives: {
      elDragDialog
    },
    data() {
      // 默认值校验
      var checkAttributeDefaultValue = (rule, value, callback) => {
        if (value) {
          const type = this.customForm.attributeType
          if (type === 'date') {
            const reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/
            if (reg.test(value)) {
              if (this.checkValidDate(value)) {
                callback()
              } else {
                callback(new Error('日期不合法'))
              }
            } else {
              callback(new Error('请输入格式正确的日期YYYY-MM-DD'))
            }
          } else if (type === 'select') {
            const result = this.customForm.optionList.filter(e => e.optionValue === value)
            if (result.length === 1) {
              callback()
            } else {
              callback(new Error('默认值必须是选项键值其中之一'))
            }
          } else if (type === 'checkbox') {
            if (value === '0' || value === '1') {
              callback()
            } else {
              callback(new Error('请输入 0 或 1 '))
            }
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      // 键值校验
      var checkOptionValue = (rule, value, callback) => {
        const reg = /^[0-9A-Za-z]+$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('只能由数字或字母组成'))
        }
      }
      return {
        // 查询表单
        searchListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          moduleCode: '',
          attributeName: '',
          attributeType: ''
        },
        dict: {
          module: {},
          attributeType: {}
        },
        // 自定义表单
        customForm: {
          attributeId: '',
          enterpriseId: this.getEnterpriseId(),
          moduleCode: '',
          attributeName: '',
          attributeType: '',
          attributeDefaultValue: '',
          attributeValueNullable: '',
          nullable: false,
          optionList: []
        },
        // 表单规则
        rules: {
          moduleCode: [
            { required: true, message: '请选择所属功能', trigger: 'blur' }
          ],
          attributeName: [
            { required: true, message: '请输入属性标题', trigger: 'blur' }
          ],
          attributeType: [
            { required: true, message: '请选择属性类型', trigger: 'blur' }
          ],
          attributeDefaultValue: [
            { validator: checkAttributeDefaultValue, trigger: 'blur' }
          ],
          optionName: [
            { required: true, message: '请输入标题', trigger: 'blur' }
          ],
          optionValue: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { validator: checkOptionValue, trigger: 'blur' }
          ]
        },
        total: null,
        listLoading: true,
        customFormVisible: false,
        dataList: [],
        // dialog标题
        dialogTitle: '',
        // 选项显示flag
        optionShowFlag: false
      }
    },
    // 初始化页面
    created() {
      getDictByGroupName('CustomAttributeDTO').then(response => {
        this.dict = response.data
        this.searchListQuery.moduleCode = Object.keys(this.dict.module)[0]
        this.initList()
      })
    },
    mounted() {
    },
    methods: {
      // 初始化
      initList() {
        if (!this.searchListQuery.moduleCode) {
          this.$message({ type: 'error', message: '请先选择功能' })
          return
        }
        this.listLoading = true
        pagingAttribute(this.searchListQuery).then(response => {
          if (response.isError) return
          this.dataList = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 查询事件
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      resetSearch() {
        this.searchListQuery = {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          moduleCode: Object.keys(this.dict.module)[0],
          attributeName: '',
          attributeType: ''
        }
        this.initList()
      },
      // 校验日期是否合法
      checkValidDate(dateStr) {
        const dateSpilt = dateStr.split('-')
        const y = dateSpilt[0]
        const m = dateSpilt[1]
        const d = dateSpilt[2]
        var result = true
        if (y > 3000) {
          return false
        }
        if (m < 1 || m > 12) {
          return false
        }
        if (d < 1 || d > 31) {
          return false
        }
        switch (d) {
          case 29:
            // 如果是2月份
            if (m === 2 && (y / 100) * 100 === y && (y / 400) * 400 !== y) {
              // 如果年份能被100整除但不能被400整除 (即闰年)
              // no do
            } else {
              result = false
            }
            break
          case 30:
            if (m === 4 || m === 6 || m === 9 || m === 11) {
              // no do
            } else {
              result = false
            }
            break
          case 31:
            if (m === 2 || m === 4 || m === 6 || m === 9 || m === 11) {
              // 2、4、6、9、11月没有31日
              result = false
            }
            break
          default:
        }
        return result
      },
      // 属性类型切换事件
      attributeTypeChange(val) {
        if (val === 'select') {
          this.optionShowFlag = true
          if (this.customForm.optionList.length === 0) this.doAddOption()
        } else {
          this.optionShowFlag = false
          this.customForm.optionList = []
        }
      },
      // 新增事件
      doAdd(row) {
        if (this.$refs['customForm']) this.$refs['customForm'].resetFields()
        if (row) {
          getAttribute(row.attributeId).then((response) => {
            if (response.isError) return
            Object.assign(this.customForm, response.data)
            this.customForm.nullable = this.customForm.attributeValueNullable === 0
            this.dialogTitle = '编辑表单属性'
            this.attributeTypeChange(this.customForm.attributeType)
            this.customFormVisible = true
          })
        } else {
          this.customForm = {
            attributeId: '',
            enterpriseId: this.getEnterpriseId(),
            moduleCode: '',
            attributeName: '',
            attributeType: '',
            attributeDefaultValue: '',
            attributeValueNullable: '',
            nullable: false,
            optionList: []
          }
          this.dialogTitle = '新增表单属性'
          this.attributeTypeChange('')
          this.customFormVisible = true
        }
      },
      // 选项新增事件
      doAddOption() {
        const option = {
          optionId: '',
          attributeId: this.customForm.attributeId,
          optionName: '',
          optionValue: ''
        }
        this.customForm.optionList.push(option)
      },
      // 选项删除事件
      doDeleteOption(option) {
        this.customForm.optionList.splice(this.customForm.optionList.indexOf(option), 1)
      },
      // 保存事件
      doSave() {
        if (this.customForm.attributeType === 'select' && this.customForm.optionList.length === 0) {
          this.$message({ type: 'error', message: '选项不能为空' })
          return
        }
        this.$refs['customForm'].validate((valid) => {
          if (valid) {
            this.customForm.attributeValueNullable = this.customForm.nullable ? 0 : 1
            saveAttribute(this.customForm).then((response) => {
              if (response.isError) return
              this.$message({ type: 'success', message: '保存成功!' })
              this.customFormVisible = false
              this.initList()
            })
          }
        })
      },
      // 排序移动事件
      doMove(row, moveType) {
        const form = {
          attributeId: row.attributeId,
          moveType: moveType
        }
        doMoveUpdate(form).then((response) => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功!' })
          this.initList()
        })
      },
      // 删除事件
      doDelete(row) {
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteAttribute({ attributeId: row.attributeId }).then(response => {
            if (response.isError) return
            this.$message({ type: 'success', message: '删除成功!' })
            this.searchListQuery.currentPage = 1
            this.initList()
          })
        }).catch(() => {
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .top-operate {
    margin-bottom: 20px;
    height: 85px;
    background-color: #f7f8fa;
    display: flex;
    align-items: center;
    white-space: nowrap;
    flex-wrap: nowrap;
    width: 100%;
    overflow-x: auto;
  }
  .option-block {
    .el-input {
      display: table-row;
    }
    /deep/ .el-form-item__label {
      padding: 0
    }
    /deep/ .el-form-item__error {
      right: 0 !important;
      left: initial !important;
    }
  }
  .search-item {
    flex-shrink: 0;
    padding: 0 20px;
    label {
      font-weight: unset;
    }
    .el-input {
      width: 200px;
    }
  }
</style>
